<?php

class GalactusModelUser extends GalactusModelGallery {

	function __construct($control) {
		GalactusModel::__construct($control);
	}

	public function active($email, $random_id) {		
		$query = $this->query(
			"SELECT id FROM User WHERE email = :email AND random_id = :random_id",
			array(":email" => $email, ":random_id" => $random_id)
		);
		if(!$query["fail"] && !empty($query)) {
			$this->query("UPDATE User SET active = 1, random_id = '' WHERE id = :user_id", array(":user_id" => $query["result"][0]["id"]));			
			echo $this->control->view->helper->alertSuccess("Sua conta foi ativada com sucesso!", URL."REDIRECT/USER/SHOW");
		}
		else throw new Exception("Falha na realização da operação!");
	}

	public function changePassword($password, $password_confirm) {
		if(!empty($password) && $password == $password_confirm) {
			$this->query(
				"UPDATE User SET password = SHA2(SHA2(:password, 512), 512) WHERE id = :user_id",
				array(':user_id' => $this->control->user_id, ":password" => $password)
			);
			if(!$query["fail"])
				echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL."REDIRECT/USER/SHOW");
			else throw new Exception("Falha na realização da operação!");
		}
		else throw new Exception("Senhas não conferem!");
	}

	public function edit($name, $email) {
		if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$name = empty($name)? reset(explode('@', $email)) : $name;
			$this->query(
				"UPDATE User SET name = :name, email = :email WHERE id = :user_id",
				array(':user_id' => $this->control->user_id, ':name' => $name, ":email" => $email)
			);
			if(!$query["fail"])
				echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL."REDIRECT/USER/SHOW");
			else throw new Exception("Falha na realização da operação!");
		}
		else throw new Exception("E-mail inválido!");
	}

	public function remove( ) {		
		$query = $this->query("DELETE FROM User WHERE id = :user_id", array(":user_id" => $this->control->user_id));
		if(!$query["fail"])
			$this->signOut( );
		else throw new Exception("Falha na realização da operação!");
	}

	public function retrieveUser($param = NULL) {
		$sql = "
			SELECT u.id AS user_id, u.name, u.profile_id, p.label AS profile, u.email, CAST(u.active AS UNSIGNED INT) AS active, u.created_on
			FROM User u
			INNER JOIN Profile AS p ON p.id = u.profile_id
			WHERE ".((!empty($param))? "(u.id = :param OR u.name = :param OR u.email = :param) AND " : NULL)." u.id != 1
			ORDER BY u.name
		";
		$query = $this->query($sql, array(":param" => $param));
		if(!$query["fail"])
			return $query["result"];
		return NULL;
	}

	public function signIn($email, $password) {
		$query = $this->query(
			"SELECT * FROM User WHERE email = :email AND password = SHA2(SHA2(:password, 512), 512) AND active = 1",
			array(':email' => $email, ':password' => $password)
		);
		if(!$query['fail'] && !empty($query['result'])) {
			session_regenerate_id( );
			$this->query(
				"UPDATE User SET session_id = :session_id WHERE id = :user_id",
				array(':session_id' => session_id( ), ':user_id' => $query['result'][0]['id'])
			);		
			$_SESSION['user_id'] = $query['result'][0]['id'];
			$_SESSION['profile_id'] = $query['result'][0]['profile_id'];
			$this->control->user_id = $_SESSION["user_id"];
			$this->control->profile_id = $_SESSION["profile_id"];
			$this->control->execute("REDIRECT", "USER");
		}
		else throw new Exception("E-mail ou senha inválidos!");
	}

	public function signOut( ) {
		session_unset( );
		session_destroy( );
		echo '<script type="text/javascript">location.href = "'.URL.'";</script>';
		exit( );
	}

	public function signUp($name, $email, $password) {
		if(filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($password)) {
			$email = strtolower($email);
			$name = empty($name)? reset(explode('@', $email)) : $name;
			$random_id = hash("sha512", mt_rand(654331, mt_getrandmax( )));
			$query = $this->query(
				"INSERT INTO User (name, email, password, profile_id, random_id) VALUES (:name, :email, SHA2(SHA2(:password, 512), 512), :profile_id, :random_id)",
				array(":name" =>$name, ":email" => $email, ":password" => $password, ":profile_id" => USER, ":random_id" => $random_id)
			);
			if(!$query["fail"]) {
				$subject = "GALACTUS: Ativação de Conta";
				$message = "Para ativar sua conta no GALACTUS, clique neste link: "."177.20.146.27/USER/ACTIVE?params[]=".$email."&params[]=".$random_id;
				mail($email, $subject, $message);
				echo $this->control->view->helper->alertSuccess("Um e-mail de ativação será enviado para você! Por favor, verifique seus spams!", URL."REDIRECT/USER/SHOW");
			}
			else throw new Exception("Falha na realização da operação!");
		}
	}

}

?>
